import java.awt.image.BufferedImage;
//import java.io.BufferedReader;
//import java.io.BufferedWriter;
import java.io.File;
//import java.io.FileReader;
//import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;

public class brightnessRecognition {

    private int height = 0;
    private int width = 0;

    public int[] readImage(String filename){

        File inputFile = new File(filename);

        BufferedImage bufferedImage = null;
        
        try {
            bufferedImage = ImageIO.read(inputFile);
        } catch (IOException ex) {
            System.out.println(ex);
        }

        width = bufferedImage.getWidth();
        height = bufferedImage.getHeight();

        // create array to store pixels
        int[] pixels = new int[width*height];

        bufferedImage.getRGB(0, 0, width, height, pixels, 0, width); //Get all pixels
        
        return pixels;
    }

    /*
     * Determines the average color of an image by averaging the value of
     * every pixel.
     */
    public long determineAvgColor(int[] im){

        /*
         * Range
         *
         * Black: -16777216
         *
         * White: -1
         *
         * Red: -65536
         */

        long sum = 0;

        for(int i=0; i < im.length; i++){
            sum += im[i];
        }

        return sum/im.length;
    }

    /*
     * Vertically slices an array (image) into the number of parts specified
     *
     *
     * Example if number of parts is 5
     * 
     ********************************************************
     *          *          *          *          *          *
     *    0     *    1     *    2     *    3     *    4     *
     *          *          *          *          *          *
     ********************************************************
     *
     * returns the number of the segment which is "brightest" - highest average pixel value
     */
    public int determineBrightestSegment(int[] im, int parts){

        // to keep track of the segment colors
        // if they're all equal, we return -1 at the end
        double[] segmentColors = new double[parts];

        if(parts <= 1){
            return 0;
        }

        int[] formatted;

        // if the image does not divide evenly into parts, we need to trim the image
        if(width%parts != 0){
            
            formatted = resizeImage(im, parts);
        }
        else{
            formatted = im;
        }
        
        int segWidth = width/parts;

        double highestValue = -20000000; // smallest possible color is -16777216
        int brightestSegment = 0;

        for(int i=0; i < parts; i++){

            double avgColor = 0;

            int tracker = i*segWidth;
            int counter = 0;

            for(int j=tracker; j < formatted.length; j++){

                if(counter < segWidth){
                    
                    avgColor += formatted[j];
                    counter++;
                }
                else{
    
                    j += ((parts-1)*segWidth)-1;
                    counter = 0;
                    
                }

            } // end j-for
            
            avgColor /= (formatted.length/parts);

            segmentColors[i] = avgColor;

            if(avgColor > highestValue){
                highestValue = avgColor;
                brightestSegment = i;
            }

        } // end i-for

        boolean allTheSame = true;

        for(int i=1; i < segmentColors.length; i++){
            
            if(segmentColors[i-1] != segmentColors[i]){
                allTheSame = false;
            }
        }

        // return -1 if all segment colors are equal
        if(allTheSame == true){
            return -1;
        }

        // if we've reached this point, then one segment is brighter than the others,
        // so return it
        return brightestSegment;

    } // end determineBrightestSegment

    /*
     * If the image can't be divided evenly into the designated number of parts,
     * trim the image until the number of parts does divide evenly.
     *
     * First from right, then from left, etc. (alternating)
     */
    public int[] resizeImage(int[] image, int p){

        int w = width;

        boolean dividesEvenly = false;

        while(dividesEvenly == false){

            w--;

            if(w%p == 0){
                dividesEvenly = true;
            }
        }

        int totalRemoved = height*(width-w);

        int wRemoved = width-w;

        int[] temp = new int[image.length-totalRemoved];

        int counter = 0;
        
        for(int i=0; i < image.length; i++){
            
            if(i%width < (width-wRemoved)){
                
                temp[counter] = image[i];
                counter++;
            }

        }

        width = w; // save the new width

        return temp;
    } // end resizeImage

    public void convertToBlackWhiteAndSave(int[] image, String filename){

        BufferedImage bufferedImage = null;
        
        File fName = new File(filename);

        try {
            bufferedImage = ImageIO.read(fName);
        } catch (IOException ex) {
            System.out.println(ex);
        }

        int black = 0x00000000;
        int white = 0xFFFFFFFF;

        int w = bufferedImage.getWidth();

        for(int i=0; i < image.length; i++){
            
            if(image[i] > -2000000){
                bufferedImage.setRGB(i % w, i / w, white);
            }
            else{
                bufferedImage.setRGB(i % w, i / w, black);
            }
            
        }

        // create a new file and write out the new image
        int dot = filename.indexOf(".");

        String name = filename.substring(0, dot);
        String ext = filename.substring(dot+1, filename.length());
        
        File output = new File(name+"-BW"+"."+ext);

        try{
            ImageIO.write(bufferedImage, ext, output);
        } catch (Exception e){}

    }

} // end class